<template>
    <div class="dashboard-flex-root">
        <!-- 左侧图表区 -->
        <div class="dashboard-main">
            <div class="dashboard-chart">
                <h3>每日新增/退住人数</h3>
                <div ref="inOutChartRef" class="chart-box"></div>
            </div>
            <div class="dashboard-chart">
                <h3>每日外出/回归/应回人数</h3>
                <div ref="returnShouldChartRef" class="chart-box"></div>
            </div>
        </div>
        <!-- 右侧信息区 -->
        <div class="dashboard-side">
            <div class="side-chart-card">
                <div class="side-title">当前在住客户数变化</div>
                <div ref="clientCountChartRef" class="side-chart-box"></div>
            </div>
            <div class="side-staff-card">
                <div class="side-title">今日职工护理次数</div>
                <el-scrollbar class="marquee-table-wrapper" ref="staffScrollbar" :height="390">
                    <table class="marquee-table">
                        <thead>
                            <tr>
                                <th>姓名</th>
                                <th>护理次数</th>
                            </tr>
                        </thead>
                        <tbody ref="marqueeBodyRef">
                            <tr v-for="item in staffList" :key="item.name">
                                <td>{{ item.name }}</td>
                                <td>{{ item.count }}</td>
                            </tr>
                        </tbody>
                    </table>
                </el-scrollbar>
            </div>
        </div>
    </div>
</template>
  
<script setup>
import { ref, onMounted, nextTick, inject, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

// === 你的 axios 实例 ===
const axios = inject('axios')

// === 图表/表格相关ref ===
const inOutChartRef = ref(null)
const returnShouldChartRef = ref(null)
const clientCountChartRef = ref(null)
const marqueeBodyRef = ref(null)
const staffScrollbar = ref(null)
const staffList = ref([])

// === 轮播滚动定时器ID ===
let scrollTimer = null

onMounted(async () => {
    // 获取接口数据（可替换成你的真实接口）
    const [checkin, checkout, leaveReturn, leaveShould, out] = await Promise.all([
        axios.get('/checkinRecord/listNum'),
        axios.get('/checkoutApply/listNum'),
        axios.get('/leaveApply/listReturnNum'),
        axios.get('/leaveApply/listShouldNum'),
        axios.get('/leaveApply/listOutNum')
    ])
    const liveClientHistory = await axios.get('/client/liveCountHistory')
    const staffCareList = await axios.get('/nursingRecord/todayCaretakerCount')
    staffList.value = staffCareList.data.data || []

    function toArr(raw) {
        if (!raw || typeof raw !== 'object') return []
        if (Array.isArray(raw)) return raw
        return Object.entries(raw).map(([date, num]) => ({ date: date.slice(0, 10), num }))
    }
    const checkinData = toArr(checkin.data.data)
    const checkoutData = toArr(checkout.data.data)
    const returnData = toArr(leaveReturn.data.data)
    const shouldData = toArr(leaveShould.data.data)
    const outData = toArr(out.data.data)


    function mergeDates(...arrs) {
        return Array.from(
            new Set(arrs.flat().map(item => item.date))
        ).sort((a, b) => a.localeCompare(b))
    }
    function alignSeriesData(allDates, arr) {
        const map = Object.fromEntries(arr.map(item => [item.date, item.num]))
        return allDates.map(d => map[d] ?? 0)
    }
    // 图表序列
    const inoutDates = mergeDates(checkinData, checkoutData)
    const inSeries = alignSeriesData(inoutDates, checkinData)
    const outSeries = alignSeriesData(inoutDates, checkoutData)
    const returnDates = mergeDates(returnData, shouldData, outData)
    const returnSeries = alignSeriesData(returnDates, returnData)
    const shouldSeries = alignSeriesData(returnDates, shouldData)
    const outSeries2 = alignSeriesData(returnDates, outData)
    const clientCountData = toArr(liveClientHistory.data.data).sort((a, b) => a.date.localeCompare(b.date))
    const clientCountDates = clientCountData.map(i => i.date)
    const clientCountSeries = clientCountData.map(i => i.num)

    await nextTick()
    setTimeout(() => {
        if (inOutChartRef.value) {
            const inOutChart = echarts.init(inOutChartRef.value)
            inOutChart.setOption({
                tooltip: { trigger: 'axis' },
                legend: { data: ['新增入住', '退住'], top: 5 },
                grid: { left: 40, right: 20, top: 40, bottom: 30 },
                xAxis: {
                    type: 'category',
                    data: inoutDates,
                    axisLabel: {
                        rotate: 0,
                        fontSize: 12,
                        formatter: v => v.replace(/(\d{4}-\d{2})-(\d{2})/, '$1\n$2')
                    }
                },
                yAxis: { type: 'value', minInterval: 1 },
                series: [
                    {
                        name: '新增入住',
                        data: inSeries,
                        type: 'line',
                        smooth: true,
                        itemStyle: { color: '#91cc75' }
                    },
                    {
                        name: '退住',
                        data: outSeries,
                        type: 'line',
                        smooth: true,
                        itemStyle: { color: '#5470c6' }
                    }
                ]
            })
            window.addEventListener('resize', () => inOutChart.resize())
        }
        if (returnShouldChartRef.value) {
            const returnShouldChart = echarts.init(returnShouldChartRef.value)
            returnShouldChart.setOption({
                tooltip: { trigger: 'axis' },
                legend: { data: ['外出', '回归', '应回'], top: 5 },
                grid: { left: 40, right: 20, top: 40, bottom: 30 },
                xAxis: {
                    type: 'category',
                    data: returnDates,
                    axisLabel: {
                        rotate: 0,
                        fontSize: 12,
                        formatter: v => v.replace(/(\d{4}-\d{2})-(\d{2})/, '$1\n$2')
                    }
                },
                yAxis: { type: 'value', minInterval: 1 },
                series: [
                    {
                        name: '回归',
                        data: returnSeries,
                        type: 'bar',
                        barWidth: 20,
                        itemStyle: { color: '#fac858' }
                    },
                    {
                        name: '应回',
                        data: shouldSeries,
                        type: 'bar',
                        barWidth: 20,
                        itemStyle: { color: '#ee6666' }
                    },
                    {
                        name: '外出',
                        data: outSeries2,
                        type: 'bar',
                        barWidth: 20,
                        itemStyle: { color: '#73c0de' }
                    }
                ]
            })
            window.addEventListener('resize', () => returnShouldChart.resize())
        }
        if (clientCountChartRef.value) {
            const clientCountChart = echarts.init(clientCountChartRef.value)
            clientCountChart.setOption({
                tooltip: { trigger: 'axis' },
                grid: { left: 35, right: 10, top: 25, bottom: 25 },
                xAxis: {
                    type: 'category',
                    data: clientCountDates,
                    axisLabel: {
                        interval: 0,     // 显示全部
                        fontSize: 9,
                        formatter: v => v.replace(/(\d{4}-\d{2})-(\d{2})/, '$1\n$2')
                    }
                },
                yAxis: { type: 'value', minInterval: 1 },
                series: [{
                    name: '在住客户数',
                    data: clientCountSeries,
                    type: 'line',
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: 8,
                    itemStyle: { color: '#2fa7ff' }
                }]
            })
            window.addEventListener('resize', () => clientCountChart.resize())
        }
    }, 80)

    nextTick(startStaffMarquee)
})

// staffList 变化时重启滚动
watch(staffList, () => {
    nextTick(() => startStaffMarquee())
})

// 离开页面清理定时器
onBeforeUnmount(() => {
    if (scrollTimer) clearInterval(scrollTimer)
})

// 自动滚动表格
function startStaffMarquee() {
    if (scrollTimer) clearInterval(scrollTimer)
    const tbody = marqueeBodyRef.value
    const scrollbar = staffScrollbar.value
    if (!tbody || !scrollbar) return
    const wrapper = scrollbar.wrapRef
    wrapper.scrollTop = 0

    // 如果内容不超出，不滚动
    if (tbody.scrollHeight <= wrapper.offsetHeight) return

    let speed = 1 // px/step
    scrollTimer = setInterval(() => {
        if (wrapper.scrollTop + wrapper.offsetHeight >= tbody.scrollHeight) {
            wrapper.scrollTop = 0 // 到底回到顶部
        } else {
            wrapper.scrollTop += speed
        }
    }, 30)

    // 悬停暂停
    wrapper.addEventListener('mouseenter', pauseScroll)
    wrapper.addEventListener('mouseleave', resumeScroll)
    function pauseScroll() { if (scrollTimer) clearInterval(scrollTimer) }
    function resumeScroll() {
        if (scrollTimer) clearInterval(scrollTimer)
        scrollTimer = setInterval(() => {
            if (wrapper.scrollTop + wrapper.offsetHeight >= tbody.scrollHeight) {
                wrapper.scrollTop = 0
            } else {
                wrapper.scrollTop += speed
            }
        }, 30)
    }
}
</script>
  
<style scoped>
.dashboard-flex-root {
    display: flex;
    flex-direction: row;
    gap: 2em;
    padding: 2em 2em 0 2em;
    background: #fff;
}

.dashboard-main {
    flex: 2.1;
    display: flex;
    flex-direction: column;
    gap: 2em;
    min-width: 300px;
}

.dashboard-chart {
    background: #f6f6f6;
    border-radius: 18px;
    padding: 1.1em 1.5em 1em 1.5em;
    box-shadow: 0 2px 18px 0 #eaeaea45;
    min-width: 0;
}

.chart-box {
    width: 100%;
    height: 250px;
    min-height: 180px;
}

.dashboard-side {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 1.5em;
    min-width: 270px;
}

.side-chart-card {
    background: #f8fafc;
    border-radius: 18px;
    box-shadow: 0 2px 16px 0 #eaeaea25;
    padding: 1em 1.1em 0 1.1em;
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 200px;
    flex-shrink: 0;
}

.side-staff-card {
    background: #f8fafc;
    border-radius: 18px;
    box-shadow: 0 2px 16px 0 #eaeaea25;
    padding: 1em 1.1em 1em 1.1em;
    display: flex;
    flex-direction: column;
    align-items: center;
    flex: 1;
    min-height: 180px;
    overflow: hidden;
}

.side-title {
    font-weight: 500;
    color: #444;
    font-size: 1.08em;
    margin-bottom: 0.3em;
}

.side-chart-box {
    width: 100%;
    height: 160px;
    flex-shrink: 0;
}

.marquee-table-wrapper {
    flex: 1;
    width: 100%;
    min-height: 120px;
}

.marquee-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 1em;
}

.marquee-table th,
.marquee-table td {
    padding: 0.25em 0.5em;
    border-bottom: 1px solid #f0f0f0;
    text-align: center;
}

.marquee-table th {
    background: #e6f7ff;
    font-weight: 600;
    position: sticky;
    top: 0;
    z-index: 2;
}

/* 隐藏 el-scrollbar 的滚动条 */
.marquee-table-wrapper .el-scrollbar__bar {
    display: none !important;
}
</style>
  